import axios from 'axios'

import store from '@/store'
import router from '@/router'
import {Message} from 'element-ui'

const req = axios.create({
  baseURL:process.env.BASE_URL,
  timeout:1000
});

//请求前的拦截代码
req.interceptors.request.use(
  config=>{

      config.headers['Content-Type'] = "application/json;charset=utf-8";

      try {
        let token = store.getters.token;
        if (token) {
          config.headers['Authorization'] = 'Bearer ' + token;
        }
      }catch(e){
        console.log("e="+e);
      }
      return config;
  },

  error => {

  }

  );

//响应到时的拦截代码
req.interceptors.response.use(
  resp=>{

    switch( resp.status){
      case 500:
              Message.error("服务器内部错误,请稍后再试!");
              break;
      case 403:
              Message.error("您没有权限访问");
              break;
      case 401:
              router.push('/login');
              break;
      case 200: return resp.data;
      default: break;
    }
    return new Promise(()=>{});

  },
  error => {
    return error;
  }

  );


export default req;

